package com.jiangruan.javaproject.service;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.bean.GetBestBlockHash;
import com.jiangruan.javaproject.bean.HotVideo;
import com.jiangruan.javaproject.bean.HotVideoCommon;
import com.jiangruan.javaproject.net.HttpUtils;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;


import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:liuzuoqiang
 * @email:2639571477@qq.com
 * @desc: 该类用于调用比特币的rpc功能，获取最新区块的哈希值
 * @datetime: 2021/12/30 0:45
 */

public class GetBestBlockHashService {

    public String getBestBlockHash(){
        //准备用户信息
        String author = Constants.BITCOIN_RPC_USER + ":"+Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
       String authorBase64 = encoder.encodeToString(author.getBytes());

        //准备请求头信息
        Map<String,String> header = new HashMap<>();
        header.put("ContentType","application/json");
        header.put("Authorization","Basic "+ authorBase64);

        //准备请求的数据
        Map<String,Object> body = new HashMap<>();
        body.put("id",1001);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");
        //将map转换为bute[]
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL, header,bodyBytes);
        //对result进行json反序列化
        System.out.println(result);
        GetBestBlockHash getBestBlockHash = JSONObject.parseObject(result, GetBestBlockHash.class);
        return getBestBlockHash.result;

    }

}
